package org.example.springcloud.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.example.springcloud.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    EurekaClient client;
    @Value("${user.url}")
    private String url;

    @GetMapping("/order/{id}")
    @HystrixCommand(fallbackMethod = "failGetUser")
    public User getUser(@PathVariable long id) {
        InstanceInfo instanceInfo = client.getNextServerFromEureka("PROVIDER-USER", false);
        String home = instanceInfo.getHomePageUrl();
        User user = restTemplate.getForObject(
                home + "/user/" + id,
                User.class
        );
        ;
        return user;
    }

    public User failGetUser(long id) {
        return new User(-1);
    }
}
